"use client";
import {
  List,
  EditButton,
  ShowButton,
  DeleteButton,
  useTable,
} from "@refinedev/antd";
import { Space, Table, Button, message, Modal, Input, Form } from "antd";
import { useEffect, useState } from "react";
import { resetUserPassword } from "@/common/api/user_action";
import { KeyOutlined } from "@ant-design/icons";

export default function UserList() {
  const [datas, setDatas] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [resetPasswordForm] = Form.useForm();
  const { tableProps, setCurrent, setPageSize, tableQueryResult } = useTable({
    resource: "system/user/list",
    syncWithLocation: true,
    pagination: {
      current: 1,
    },
  });

  useEffect(() => {
    const res = tableProps?.dataSource as any;
    if (res && res.data) {
      const { list, total } = res.data;
      setDatas(list);
      setTotal(total);
    }
  }, [tableProps?.dataSource]);

  const handleResetPassword = (userId: number, userName: string) => {
    Modal.confirm({
      title: '重置密码',
      content: (
        <Form form={resetPasswordForm} layout="vertical">
          <Form.Item
            label="新密码"
            name="newPassword"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 6, message: '密码长度至少6位' }
            ]}
          >
            <Input.Password placeholder="请输入新密码" />
          </Form.Item>
          <Form.Item
            label="确认密码"
            name="confirmPassword"
            dependencies={['newPassword']}
            rules={[
              { required: true, message: '请确认密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password placeholder="请再次输入新密码" />
          </Form.Item>
        </Form>
      ),
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          const values = await resetPasswordForm.validateFields();
          await resetUserPassword(userId, values.newPassword);
          message.success('密码重置成功');
          resetPasswordForm.resetFields();
          // 刷新表格数据
          tableQueryResult?.refetch();
        } catch (error: any) {
          if (error.errorFields) {
            // 表单验证错误，不显示错误消息
            return Promise.reject();
          }
          message.error(error.message || '重置密码失败');
        }
      }
    });
  };

  return (
    <List>
      <Table dataSource={datas} rowKey="user_id" loading={tableProps?.loading} pagination={{
        showTotal: (total, range) => `总共 ${total} 条`,
        pageSize: 10,
        total: total,
        onChange: (page, pageSize) => {
          setCurrent(page);
          setPageSize(pageSize);
        },
      }}>
        <Table.Column dataIndex="user_id" title={"用户ID"} />
        <Table.Column dataIndex="user_name" title={"用户名"} />
        <Table.Column dataIndex="nick_name" title={"昵称"} />
        <Table.Column dataIndex="email" title={"邮箱"} />
        <Table.Column dataIndex="phonenumber" title={"手机号"} />
        <Table.Column dataIndex="status" title={"状态"} />
        <Table.Column dataIndex="remark" title={"备注"} />
        <Table.Column
          title={"操作"}
          dataIndex="actions"
          render={(_, record) => {
            const isProtected = record.user_id === 1;
            return (
              <Space>
                <EditButton 
                  hideText 
                  size="small" 
                  recordItemId={record.user_id}
                  disabled={isProtected}
                  title={isProtected ? "系统管理员不可编辑" : "编辑"}
                />
                <ShowButton 
                  hideText 
                  size="small" 
                  recordItemId={record.user_id}
                  title="查看"
                />
                <Button
                  type="text"
                  size="small"
                  icon={<KeyOutlined />}
                  disabled={isProtected}
                  title={isProtected ? "系统管理员不可重置密码" : "重置密码"}
                  onClick={() => handleResetPassword(record.user_id, record.user_name)}
                />
                <DeleteButton 
                  hideText 
                  size="small" 
                  recordItemId={record.user_id}
                  disabled={isProtected}
                  title={isProtected ? "系统管理员不可删除" : "删除"}
                />
              </Space>
            );
          }}
        />
      </Table>
    </List>
  );
} 